﻿namespace FlickrDownloadr
{
    using System;
    using System.Collections.Generic;
    using Autofac;
    using Caliburn.Micro;
    using FlickrDownloadr.Features.Shell;

    public class ClientBootstrap : Bootstrapper<IShell>
    {
        IContainer _container;

        protected override void Configure()
        {
            ObjectContainer container = new ObjectContainer();
            _container = container.Build();
        }

        protected override void OnExit(object sender, EventArgs e)
        {
            Properties.Settings.Default.Save();

            base.OnExit(sender, e);
        }

        protected override void BuildUp(object instance)
        {
            _container.InjectProperties(instance);
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return _container.Resolve(typeof(IEnumerable<>).MakeGenericType(service)) as IEnumerable<object>;
        }

        protected override object GetInstance(Type service, string key)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                if (_container.IsRegistered(service))
                {
                    return _container.Resolve(service);
                }
            }
            else
            {
                if (_container.IsRegistered(key, service))
                {
                    return _container.Resolve(key, service);
                }
            }

            throw new Exception(string.Format("Could not locate any instances of contract {0}.", key ?? service.Name));
        }
    }
}
